package com.tianji.learning.utils;

import lombok.Data;

import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2024/6/23 16:03
 */
@Data
public class DelayTask<D> implements Delayed {

    private Long deadLineNanos; // 延迟执行时间的纳秒值
    private D data; // 延时任务数据

    public DelayTask(Duration duration, D data) {
        this.deadLineNanos = System.nanoTime() + duration.toNanos();
        this.data = data;
    }

    /**
     * 1、用来获取当前这个任务距离当前时间还有多少【纳秒】被执行
     * @param unit the time unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(Math.max(0,deadLineNanos - System.nanoTime()),TimeUnit.NANOSECONDS);
    }

    /**
     * 对延迟队列中的任务进行排序（排序依据：根据getDelay获取任务的延时时间来排，值越小，越先被执行）
     * @param o the object to be compared.
     * @return
     */
    @Override
    public int compareTo(Delayed o) {
        long diff = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        if(diff > 0){
            return 1;
        }else if(diff == 0){
            return 0;
        }else{
            return -1;
        }
    }
}
